<template>
  <div class="ma-content-block lg:flex justify-between p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #tableAfterButtons>
        <a-button type="primary" @click="loadMachineMaps()">
          <template #icon>
            <icon-cloud-download />
          </template>
          <!-- Use the default slot to avoid extra spaces -->
          <template #default>加载当前设备地图数据</template>
        </a-button>
        <!-- <a-button>后置扩展操作B</a-button> -->
      </template>

      <template #operationBeforeExtend="{ record }">
        <a-link @click="useCurrentMap(record)" status="warning" v-if="record.is_current == 0">
          <template #icon>
            <icon-expand />
          </template>
          <span>应用地图</span>

        </a-link>
        <a-link status="primary" v-else>
          <template #icon>
            <icon-expand />
          </template>
          <span>已应用</span>
        </a-link>

        <a-link @click="remameMapName(record)" status="warning">
          <template #icon>
            <icon-translate />
          </template>
          重命名地图
        </a-link>
        <!-- <a-button>新增</a-button> -->
      </template>
      <!-- 状态列 -->
      <template #is_current="{ record }">
        <a-tag color="blue" v-if="record.is_current == 1">是</a-tag>
        <a-tag color="red" v-else>否</a-tag>
      </template>
      <template #operationCell="{ record }">

<a-popconfirm content="你确定要删除该地图吗,请谨慎操作？" @ok="deleteMap(record)">
  <a-button type="text" status="danger" size="small">
  <template #icon>
    <icon-delete />
  </template>
  <!-- Use the default slot to avoid extra spaces -->
  <template #default>删除</template>
</a-button>
</a-popconfirm>

</template>
    </ma-crud>
    <a-modal v-model:visible="visibleRename" title="地图名更新" @before-ok="submitRename" @ok="realSubmitRename">
      <a-form :model="form">
        <a-form-item field="name" label="地图别名" :rules="[{ required: true, message: '地图别名不能为空' }]">
          <a-input v-model="form.name" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted,watch ,defineEmits} from 'vue'
import systemDeviceMap from '@/api/system/systemDeviceMap'
import { Message } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import * as common from '@/utils/common'

const crudRef = ref()
const topic = ref();
const props = defineProps(["client", "curDevieInfo","isSuccess"]);
const clientMap = ref();
const cur_map  = ref()

const emits = defineEmits()
// const isActive = props.isSuccess
const form = reactive({
  name: ''
});

watch(() => props.isSuccess, (newVal, oldVal) => {
  console.log(`count 变化了，新值: ${newVal}, 旧值: ${oldVal}`);
  crudRef.value.refresh()
});

console.log(props.client);
const visibleRename = ref(false)
topic.value = "PERSONDEVICE/" + props.curDevieInfo.device_num
const generateUniqueKey = () => {
  let key = 'key_';
  const time = Date.now().toString(36);
  const random = Math.random().toString(36).substr(2, 9);
  return key + time + random;
}

onMounted(() => {

  

})

//删除地图操作
const deleteMap = (record)=>{
  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@map@delmap",params:{map_name:record.map_name}, message_id: message_id, remark: "del_map" }),"删除地图操作", "del_map", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@map@delmap",params:{map_name:record.map_name}, message_id: message_id, remark: "del_map" }));
  Message.loading("正在删除导航地图。。")

}

const loadOrderResult = (order_name, name, remark, message_id) => {

  let orderArr = {
    name: name,
    order_name: order_name,
    created_at: tool.dateFormat(new Date),
    device_num: props.curDevieInfo.device_num,
    message_id: message_id,
    remark: remark,
    order_result: "",
    isload: 2
  }
}
//发送获取地图列表的命令
const loadMachineMaps = () => {
  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@map@list", message_id: message_id, remark: "maplist" }),"加载机器人地图列表", "maplist", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@map@list", message_id: message_id, remark: "maplist" }));
  Message.loading("正在加载导航地图中")
  setTimeout(()=>{
    console.log("refresh")
    crudRef.value.refresh()
  },2000)
}
const numberOperation = (newValue, id, numberName) => {
  systemDeviceMap.numberOperation({ id, numberName, numberValue: newValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}
const switchStatus = (statusValue, id, statusName) => {
  systemDeviceMap.changeStatus({ id, statusName, statusValue }).then(res => {
    res.success && Message.success(res.message)
  }).catch(e => { console.log(e) })
}

//地图别名更新前置
const submitRename = (done) => {
  if (form.name == "") {
    Message.error("地图别名不能为空")
    return false
  }
  done()
}
//地图别名更新
const realSubmitRename = ()=>{
  emits("mapNameSet",form.name)
  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@map@rename","params":  { "mapName": cur_map.value.map_name,"alias":form.name }, message_id: message_id, remark: "map_rename" }),"地图重命名", "map_rename", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@map@rename", "params": { "mapName": cur_map.value.map_name,"alias":form.name },message_id:message_id,remark:"map_rename" }));
 
  // setTimeout(()=>{
  //   console.log("refresh")
  //   crudRef.value.refresh()
  // },2000)
}

//应用当前地图
const useCurrentMap = (record) => {

  let message_id = generateUniqueKey();
  loadOrderResult(JSON.stringify({ order: "machine@map@selected", message_id: message_id, remark: "mapSelected" }),"应用地图", "mapSelected", message_id)
  props.client.publish(topic.value, JSON.stringify({ order: "machine@map@selected", "params": { "mapName": record.map_name } ,message_id:message_id,remark: "mapSelected"}));
  // setTimeout(()=>{
  //   console.log("refresh")
  //   crudRef.value.refresh()
  // },2000)

}

//重命名地图
const remameMapName = (record) => {
  visibleRename.value = true
  cur_map.value = record
 
}
const options = reactive({

  // 设置前置请求
  beforeRequest: params => {
    // 指定排序字段为浏览量字段
    params.orderBy = 'id'
    // 指定降序排序
    params.orderType = 'desc'

    params.device_num = props.curDevieInfo.device_num
  },
  id: 'system_device_map',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  operationColumn: true,
  operationWidth: 160,
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: systemDeviceMap.getList,
  recycleApi: systemDeviceMap.getRecycleList,
  add: {
    show: false,
    api: systemDeviceMap.save,
    auth: ['system:deviceMap:save']
  },
  edit: {
    show: false,
    api: systemDeviceMap.update,
    auth: ['system:deviceMap:update']
  },
  delete: {
    show: false,
    api: systemDeviceMap.deletes,
    auth: ['system:deviceMap:delete'],
    realApi: systemDeviceMap.realDeletes,
    realAuth: ['system:deviceMap:realDeletes']
  },
  recovery: {
    show: true,
    api: systemDeviceMap.recoverys,
    auth: ['system:deviceMap:recovery']
  },
  import: {
    show: false,
    url: 'system/deviceMap/import',
    templateUrl: 'system/deviceMap/downloadTemplate',
    auth: ['system:deviceMap:import']
  },
  export: {
    show: true,
    url: 'system/deviceMap/export',
    auth: ['system:deviceMap:export']
  }
})

const columns = reactive([
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    }
  },
  {
    title: "地图名称",
    dataIndex: "map_name",
    formType: "input",
    search: true
  },
  {
    title: "地图别名",
    dataIndex: "alias",
    formType: "input",
    search: true
  },
  {
    title: "当前地图",
    dataIndex: "is_current",
    formType: "input",
    search: false
  },
  {
    title: "设备编号",
    dataIndex: "device_num",
    formType: "input",
    search: true
  },
  {
    title: "地图宽度",
    dataIndex: "width",
    formType: "input"
  },
  {
    title: "地图高度",
    dataIndex: "height",
    formType: "input"
  },
  {
    title: "地图中心点",
    dataIndex: "resolution",
    formType: "input"
  },
  {
    title: "X坐标",
    dataIndex: "origin_ x",
    formType: "input"
  },
  {
    title: "Y坐标",
    dataIndex: "origin_y",
    formType: "input"
  },
  {
    title: "所属点位",
    dataIndex: "point_id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "所属区域",
    dataIndex: "dept_id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "地图图片",
    dataIndex: "image_url",
    formType: "upload",
    hide: false,
    type: "image",
    multiple: false
  }
])
</script>
<script>export default { name: 'system:deviceMap' } </script>